package com.mavenq.fly.websocket.handler;

import com.mavenq.fly.utils.JsonUtils;
import com.mavenq.fly.websocket.service.WSConnectionService;
import com.mavenq.fly.websocket.entity.WSMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
@Component
public class RoutingWebSocketHandler extends AbstractWSHandler {

    public RoutingWebSocketHandler(WSConnectionService connectionService) {
        super(connectionService);
    }

    @Override
    protected void onMessage(WebSocketSession session, WSMessage msg) {
        String token = (String) session.getAttributes().get("token");

        if ("auth".equalsIgnoreCase(msg.getType())) {
            if (msg.getToken() == null || msg.getToken().isEmpty()) {
                sendError(session, "auth失败：token为空");
                return;
            }
            // 更新token绑定
            connectionService.unregister(token);
            connectionService.register(msg.getToken(), session);
            connectionService.bindUserId(msg.getToken(), msg.getUserId(), session);
            sendText(session, JsonUtils.toJson(WSMessage.auth(msg.getToken(), msg.getUserId())));
            log.info("用户认证：旧token={} -> 新token={} -> userId={}", token, msg.getToken(), msg.getUserId());
            return;
        }

        if ("ping".equalsIgnoreCase(msg.getType())) {
            sendPong(session);
            return;
        }

        if ("broadcast".equalsIgnoreCase(msg.getType())) {
            connectionService.broadcast(msg);
            log.info("用户广播：userId={}, type={}, content={}", msg.getUserId(), msg.getType(), msg.getContent());
            return;
        }

        if ("uni".equalsIgnoreCase(msg.getType())) {
            if (msg.getUserId() == null || msg.getUserId().isEmpty()) {
                sendError(session, "单播失败：缺少userId");
                return;
            }
            connectionService.sendToUser(msg.getUserId(), msg);
            log.info("用户单播：from={} -> to={}，内容={}", msg.getUserId(), msg.getUserId(), msg.getContent());
            return;
        }

        sendError(session, "未知消息类型：" + msg.getType());
    }

    private void sendError(WebSocketSession session, String content) {
        try {
            if (session.isOpen()) {
                session.sendMessage(new TextMessage(JsonUtils.toJson(new WSMessage("error", null, null, content))));
            }
        } catch (Exception e) {
            log.error("发送错误消息失败", e);
        }
    }
}